package com.example.demo.exception;

import com.example.demo.constant.Constant;
import com.example.demo.util.ResultUtil;
import com.example.demo.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 *@Description 全局异常拦截
 *@Author Levi
 *@Date 2019/4/23-14:12
*/
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandle {
    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult handle(Exception e){
        ApiResult apiResult = null;
        if(e instanceof DemoServiceException){
            log.warn("[DEMO异常]",e);
            apiResult = ResultUtil.error(((DemoServiceException) e).getCode(), e.getMessage());
        }else{
            log.error("[系统异常]",e);
            apiResult = ResultUtil.error(Constant.STATUS_ERROR, e.getMessage());
        }
        return apiResult;
    }
}
